package org.pentaho.huaweicloud;

import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
import org.pentaho.di.connections.ConnectionManager;
import org.pentaho.di.connections.vfs.VFSLookupFilter;
import org.pentaho.di.core.annotations.KettleLifecyclePlugin;
import org.pentaho.di.core.lifecycle.KettleLifecycleListener;
import org.pentaho.di.core.lifecycle.LifecycleException;
import org.pentaho.di.core.logging.LogChannel;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.huaweicloud.obs.provider.OBSProvider;
import org.pentaho.obs.vfs.OBSFileProvider;

import java.util.Arrays;
import java.util.function.Supplier;

@KettleLifecyclePlugin( id = "HWOBSFileSystemBootstrap", name = "HuaweiCloud OBS FileSystem Bootstrap" )
public class HWOBSFileSystemBootstrap implements KettleLifecycleListener {
    private static Class<?> PKG = HWOBSFileSystemBootstrap.class;
    private LogChannelInterface log = new LogChannel( HWOBSFileSystemBootstrap.class.getName() );
    private Supplier<ConnectionManager> connectionManager = ConnectionManager::getInstance;

    /**
     * @return the i18n display text for the OBS file system
     */
    public static String getOBSFileSystemDisplayText() {
        return BaseMessages.getString( PKG, "OBSVfsFileChooserDialog.FileSystemChoice.OBS.Label" );
    }


    @Override
    public void onEnvironmentInit() throws LifecycleException {
        try {
            // Register OBS as a file system type with VFS
            FileSystemManager fsm = KettleVFS.getInstance().getFileSystemManager();
            if ( fsm instanceof DefaultFileSystemManager && !Arrays.asList( fsm.getSchemes() )
                    .contains( OBSFileProvider.SCHEME ) ) {
                ( (DefaultFileSystemManager) fsm ).addProvider( OBSFileProvider.SCHEME, new OBSFileProvider() );
            }

            if ( connectionManager.get() != null ) {
                connectionManager.get().addConnectionProvider( OBSFileProvider.SCHEME, new OBSProvider() );
                VFSLookupFilter vfsLookupFilter = new VFSLookupFilter();
                connectionManager.get().addLookupFilter( vfsLookupFilter );
            }
        } catch ( FileSystemException e ) {
            log.logError( BaseMessages
                    .getString( PKG, "HWSpoonPlugin.StartupError.FailedToLoadOBSDriver" ) );
        }
    }


    @Override
    public void onEnvironmentShutdown() {
        // noop
    }
}
